package com.ydsungan.controller;

import com.ydsungan.common.DateUtils;
import com.ydsungan.common.JSONResult;

import com.ydsungan.pojo.*;
import com.ydsungan.service.BookService;
import com.ydsungan.service.HomeService;
import com.ydsungan.service.QuestionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping(path = "/question")
@Api(value = "题目相关",tags = {"与题目相关的接口"})
public class QuestionController extends BasicController{


    @Autowired
    private QuestionService questionService;

    @Autowired
    private BookService bookService;

    @Autowired
    private HomeService homeService;




    @ApiOperation(value="做题",notes = "获取5道题目")
    @RequestMapping(value = "/practice", method = RequestMethod.GET)
    public JSONResult practice(String chapterId, String openId) throws Exception{
        // openid:chapterId    questionId
        QuestionExample questionExample = new QuestionExample();
        QuestionExample.Criteria questionCriteria = questionExample.createCriteria();
        String questionId = redis.get(openId + ":" + chapterId);
        List<Question> questionList = new ArrayList<Question>();
        List<Question> resultList ;

        if(questionId == null){
            questionCriteria.andChapterIdEqualTo(Integer.parseInt(chapterId));
        }else{
            questionCriteria.andChapterIdEqualTo(Integer.parseInt(chapterId));
            questionCriteria.andIdGreaterThan(Integer.parseInt(questionId));
        }
        resultList = questionService.listQuestion(questionExample);
        if(resultList.size() < 5){
            for(int i = 0; i < resultList.size(); ++i){
                questionList.add(resultList.get(i));

            }
        }else{
            for(int i = 0; i < 5; ++i){
                questionList.add(resultList.get(i));

            }
        }

        return JSONResult.ok(questionList);
    }

    @ApiOperation(value="错题本",notes = "获取错题本")
    @RequestMapping(value = "/errorset", method = RequestMethod.GET)
    public JSONResult getErrorBook(String openId) throws Exception{

        List<Book> bookList = bookService.selectUsingBook(openId);

        List<String> jsonObjectList = new ArrayList<>();
        for(int i = 0; i < bookList.size(); ++i){

            PracticeExample practiceExample = new PracticeExample();
            PracticeExample.Criteria criteria2 = practiceExample.createCriteria();
            criteria2.andBookIdEqualTo(bookList.get(i).getId());
            criteria2.andIsRightEqualTo(0);
            criteria2.andUserIdEqualTo(openId);
            criteria2.andStatusEqualTo(1);
            int wrongNum = (int)questionService.countPracticeByChapterId(practiceExample);

            JSONObject json = new JSONObject();
            json.put("bookName", bookList.get(i).getBookName());
            json.put("bookId", bookList.get(i).getId());
            json.put("wrongNum", wrongNum);
            jsonObjectList.add(json.toString());
        }

        return JSONResult.ok(jsonObjectList);
    }

    @ApiOperation(value="删除错题",notes = "将status字段修改为0")
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public JSONResult delete(String openId,  String practiceId) throws Exception {
        Practice practice = new Practice();
        practice.setStatus(0);
        practice.setId(Integer.parseInt(practiceId));
        questionService.updatePracticeSelective(practice);
        return JSONResult.ok();
    }
    @ApiOperation(value="保存复习记录",notes = "保存复习记录即可")
    @RequestMapping(value = "/checkreview", method = RequestMethod.GET)
    public JSONResult checkreview(String openId, String bookId, String idArray) throws Exception {
        String idList[] = idArray.split(",");
        for(int i = 0; i < idList.length; ++i){
            Review review = new Review();
            review.setBookId(Integer.parseInt(bookId));
            review.setCreateTime(new Date());
            review.setQuestionId(Integer.parseInt(idList[i]));
            review.setUserId(openId);
            questionService.insertReviewRecord(review);
        }
        //review:openid:2020-10-21:bookid:[1,2,3,4,5,6]
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date day = new Date();
        String dayString = df.format(day);
        String key = "review:" + openId + ":" + dayString + ":" + bookId;
        String value = "";
        String redisValue = redis.get(key);
        String idarr[] = redisValue.split(",");
        int length = 5;
        if(idarr.length < 5){
            length = idarr.length;
        }
        for(int i = length; i < idarr.length; ++i){
            if(i == idarr.length - 1){
                value += idarr[i];
            }else{
                value += idarr[i] + ",";
            }
        }
        redis.set(key, value, 24*60*60*1000);
        return JSONResult.ok();
    }

    @ApiOperation(value="检查答案",notes = "校验答案,把练习记录存进数据库")
    @RequestMapping(value = "/check", method = RequestMethod.GET)
    public JSONResult check(String chapterId, String openId, String bookId, String idArray, String answerArray, String rightArray) throws Exception{
        String  answerList[] = answerArray.split(",");
        String idList[] = idArray.split(",");
        String rightList[] = rightArray.split(",");
        int questionNum = answerList.length;

        UsedExample usedExample = new UsedExample();
        UsedExample.Criteria usedCriteria = usedExample.createCriteria();
        usedCriteria.andUserIdEqualTo(openId);
        usedCriteria.andBookIdEqualTo(Integer.parseInt(bookId));
        List<Used> usedList = bookService.listUsingBook(usedExample);
        if(usedList.size() == 0){
            Used used = new Used();
            used.setUserId(openId);
            used.setBookId(Integer.parseInt(bookId));
            questionService.insertUsingRecord(used);
        }
        Date date = new Date();
        for(int i = 0; i < questionNum; ++i){
            Practice practice = new Practice();
            practice.setBookId(Integer.parseInt(bookId));
            practice.setChapterId(Integer.parseInt(chapterId));
            practice.setCreateTime(date);
            practice.setUserId(openId);
            practice.setQuestionId(Integer.parseInt(idList[i]));
            practice.setSelectedOption(answerList[i]);
            practice.setIsRight(answerList[i].equals(rightList[i]) ? 1 : 0);
            practice.setStatus(1);
            questionService.insertRecord(practice);

            Question question = questionService.findQuestionById(Integer.parseInt(idList[i]));

            Question resQuestion = new Question();
            resQuestion.setId(Integer.parseInt(idList[i]));
            resQuestion.setPracticeCounts(question.getPracticeCounts() + 1);
            if(answerList[i].equals(rightList[i])){
                resQuestion.setRightAnswerCounts(question.getRightAnswerCounts() + 1);
            }
            questionService.updateQuestion(resQuestion);
        }
        //把最后一题的id号存进redis
        redis.set(openId + ":" + chapterId, idList[questionNum - 1]);

        return JSONResult.ok();
    }

    @ApiOperation(value="获取错题",notes = "分页获取错题本题目")
    @RequestMapping(value = "/error", method = RequestMethod.GET)
    public JSONResult getErrorByPage(String openId, String bookId, String start, String offset) throws Exception{

        PracticeExample practiceExample = new PracticeExample();
        PracticeExample.Criteria criteria = practiceExample.createCriteria();
        criteria.andBookIdEqualTo(Integer.parseInt(bookId));
        criteria.andUserIdEqualTo(openId);
        criteria.andIsRightEqualTo(0);
        criteria.andStatusEqualTo(1);
        List<Practice> practiceList = questionService.listPractice(practiceExample);
        List<ErrorQuestion> errorQuestionList = new ArrayList<>();
        Book book = bookService.getBookById(Integer.parseInt(bookId));
        List<Practice> copyPracticeList = new ArrayList<>();
        int length = Integer.parseInt(start) + Integer.parseInt(offset) > practiceList.size() ? practiceList.size() - Integer.parseInt(start) : Integer.parseInt(offset);
        for(int i = 0; i < length; ++i){
            copyPracticeList.add(practiceList.get(Integer.parseInt(start) + i));
        }
        for(int i = 0; i < copyPracticeList.size(); ++i){
            Chapter chapter = bookService.getChapterById(copyPracticeList.get(i).getChapterId());
            Question question = questionService.findQuestionById(copyPracticeList.get(i).getQuestionId());
            ErrorQuestion errorQuestion = new ErrorQuestion();
            BeanUtils.copyProperties(question, errorQuestion);
            errorQuestion.setCreateTime(copyPracticeList.get(i).getCreateTime());
            errorQuestion.setPracticeId(copyPracticeList.get(i).getId());
            errorQuestion.setSelectedOption(copyPracticeList.get(i).getSelectedOption());
            String multiple = question.getMultiple() == 1 ? "多选" : "单选";
            String title = book.getAbbr() + "-" + chapter.getAbbr() + "-" + multiple;
            errorQuestion.setTitle(title);

            DecimalFormat decimalFormat = new DecimalFormat(".00");
            String rateString = decimalFormat.format((float)question.getRightAnswerCounts()/question.getPracticeCounts());
            int rate = (int)(Double.parseDouble(rateString) * 100);
            errorQuestion.setRate(rate);

            errorQuestionList.add(errorQuestion);
        }
        return JSONResult.ok(errorQuestionList);
    }

    @ApiOperation(value="获取10天内的做题数量",notes = "练习记录页面数据")
    @RequestMapping(value = "/tendays", method = RequestMethod.GET)
    public JSONResult getTenDaysCounts(String openId) throws Exception {

        String days = redis.get("days");
        List<String> records = new ArrayList<>();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat df2 = new SimpleDateFormat("MM月dd日");

        for(int i = 0; i < Integer.parseInt(days); ++i){
            Date day = new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24 * i);
            String dayString = df.format(day);
            String date = df2.format(day);



            List<Date> timeList = DateUtils.getDateStartAndEnd(i);

            PracticeExample practiceExample = new PracticeExample();
            PracticeExample.Criteria criteria = practiceExample.createCriteria();
            criteria.andCreateTimeBetween(timeList.get(0), timeList.get(1));
            criteria.andUserIdEqualTo(openId);
            int count = (int)questionService.countPracticeByChapterId(practiceExample);

            JSONObject json = new JSONObject();
            json.put("count", count);
            json.put("date", date);
            records.add(json.toString());


        }

        return JSONResult.ok(records);
    }


    @ApiOperation(value="复习错题",notes = "获取错题")
    @RequestMapping(value = "/review", method = RequestMethod.GET)
    public JSONResult reviewError(String openId,  String bookId) throws Exception {

        //review:openid:2020-10-21:bookid:[1,2,3,4,5,6]
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date day = new Date();
        String dayString = df.format(day);
        String key = "review:" + openId + ":" + dayString + ":" + bookId;

        List<Question> questionList = new ArrayList<>();
        String value = "";
        if(redis.get(key) == null){
            List<Integer> reviewQuestionsList = questionService.getReviewQuestionsList(openId, bookId);
            //reviewQuestionsList取其前5个题目
            int length = 5;
            if(reviewQuestionsList.size() < 5){
                length = reviewQuestionsList.size();
            }
            for(int i = 0; i < length; ++i){
                Question question = questionService.findQuestionById(reviewQuestionsList.get(i));
                questionList.add(question);
            }
            //reviewQuestionsList前length个元素去掉，然后把剩余元素用,链接；再存到redis
            for(int i = 0; i < reviewQuestionsList.size(); ++i){
                if(i == reviewQuestionsList.size() - 1){
                    value += reviewQuestionsList.get(i);
                }else{
                    value += reviewQuestionsList.get(i) + ",";
                }
            }
            redis.set(key, value, 24*60*60*1000);

        }else{
            String redisValue = redis.get(key);
            String idArray[] = redisValue.split(",");
            int length = 5;
            if(idArray.length < 5){
                length = idArray.length;
            }
            for(int i = 0; i < length; ++i){
                Question question = questionService.findQuestionById(Integer.parseInt(idArray[i]));
                questionList.add(question);
            }
            //idArray前length个元素去掉，然后把剩余元素用,链接；再存到redis
//            for(int i = length; i < idArray.length; ++i){
//                if(i == idArray.length - 1){
//                    value += idArray[i];
//                }else{
//                    value += idArray[i] + ",";
//                }
//            }
        }
        //redis.set(key, value, 24*60*60*1000);
        return JSONResult.ok(questionList);
    }

    @ApiOperation(value="根据ID获取题目",notes = "根据ID获取题目")
    @RequestMapping(value = "/getq", method = RequestMethod.GET)
    public JSONResult getQuestionById(String questionId, String openId) throws Exception {
        Question question = questionService.findQuestionById(Integer.parseInt(questionId));
        ErrorQuestion errorQuestion = new ErrorQuestion();
        BeanUtils.copyProperties(question, errorQuestion);

        PracticeExample practiceExample = new PracticeExample();
        PracticeExample.Criteria criteria = practiceExample.createCriteria();
        criteria.andUserIdEqualTo(openId);
        criteria.andQuestionIdEqualTo(Integer.parseInt(questionId));
        List<Practice> practiceList = questionService.listPractice(practiceExample);

        if(practiceList.size() != 0){
            errorQuestion.setSelectedOption(practiceList.get(0).getSelectedOption());
            errorQuestion.setCreateTime(practiceList.get(0).getCreateTime());
            errorQuestion.setPracticeId(practiceList.get(0).getId());
        }else{
            errorQuestion.setSelectedOption("您未作答");
        }

        DecimalFormat decimalFormat = new DecimalFormat(".00");
        String rateString = decimalFormat.format((float)question.getRightAnswerCounts()/question.getPracticeCounts());
        int rate = (int)(Double.parseDouble(rateString) * 100);
        errorQuestion.setRate(rate);
        return JSONResult.ok(errorQuestion);
    }


}
